package com.vgmobile.cucrever2.mapstore;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentSender;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.provider.Settings;
import android.view.KeyEvent;

import com.google.android.gms.common.ConnectionResult;
import com.google.android.gms.common.GooglePlayServicesClient;
import com.google.android.gms.common.GooglePlayServicesUtil;
import com.google.android.gms.location.LocationClient;
import com.google.android.gms.location.LocationListener;
import com.google.android.gms.location.LocationRequest;

public class GPS implements LocationListener, GooglePlayServicesClient.ConnectionCallbacks, GooglePlayServicesClient.OnConnectionFailedListener {

	private Activity activity;
	public Location mLocation;
    // A request to connect to Location Services
    private LocationRequest mLocationRequest;

    // Stores the current instantiation of the location client in this object
    private LocationClient mLocationClient;
    boolean mUpdatesRequested = false;
    
    public GPS(Activity activity){
    	this.activity = activity;
    	
    	// Create a new global location parameters object
        mLocationRequest = LocationRequest.create();

        /*
         * Set the update interval
         */
        mLocationRequest.setInterval(LocationUtils.UPDATE_INTERVAL_IN_MILLISECONDS);

        // Use high accuracy
        mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY);

        // Set the interval ceiling to one minute
        mLocationRequest.setFastestInterval(LocationUtils.FAST_INTERVAL_CEILING_IN_MILLISECONDS);
        
        mLocationRequest.setSmallestDisplacement(LocationUtils.MIN_DISTANCE_CHANGE_FOR_UPDATES);
        
        // Note that location updates are off until the user turns them on
        mUpdatesRequested = true;

        /*
         * Create a new location client, using the enclosing class to
         * handle callbacks.
         */
        mLocationClient = new LocationClient(activity, this, this);

        mLocationClient.connect();
    }

    public void startUpdates() {
    	if(!mUpdatesRequested){
	        mUpdatesRequested = true;
	        if (servicesConnected()) {
	            startPeriodicUpdates();
	        }
    	}
    }

    public void stopUpdates() {
    	if(mUpdatesRequested){
	        mUpdatesRequested = false;
	        if (servicesConnected()) {
	            stopPeriodicUpdates();
	        }
    	}
    }
    
    private void startPeriodicUpdates() {
        mLocationClient.requestLocationUpdates(mLocationRequest, this);
    }

    private void stopPeriodicUpdates() {
        mLocationClient.removeLocationUpdates(this);
    }
    
    public void setActivity(Activity activity){
    	this.activity = activity;
    }
    
	public boolean canGetLocation() {
		LocationManager locationManager = (LocationManager) activity.getSystemService(Activity.LOCATION_SERVICE);

		// getting GPS status
		boolean isGPSEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);

		// getting network status
		boolean isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

		if (!isGPSEnabled || !isNetworkEnabled) {
			return false;
		} else {
			return true;
		}
	}
    
	@SuppressWarnings("deprecation")
	public void showSettingsAlert(){
		AlertDialog alertDialog = new AlertDialog(activity){
			@Override
	        public boolean onKeyDown(int keyCode, KeyEvent event) {
	            if(keyCode == KeyEvent.KEYCODE_BACK) {
	            	return true;
	            }
	            return super.onKeyDown(keyCode, event);
	        }
		};
   	 
        // Setting Dialog Title
        alertDialog.setTitle("Cài đặt định vị.");
 
        // Setting Dialog Message
        alertDialog.setMessage("Bạn cần đánh dấu đầy đủ để bật chế độ định vị của ứng dụng.");
 
        alertDialog.setCanceledOnTouchOutside(false);
        
        // On pressing Settings button
        alertDialog.setButton("Cài đặt", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int which) {
            	Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            	activity.startActivity(intent);
            }
        });
 
        // Showing Alert Message
        alertDialog.show();
	}
    
    private boolean servicesConnected() {

        // Check that Google Play services is available
        int resultCode =
                GooglePlayServicesUtil.isGooglePlayServicesAvailable(activity);

        // If Google Play services is available
        if (ConnectionResult.SUCCESS == resultCode) {

            return true;
        // Google Play services was not available for some reason
        } else {
            // Display an error dialog
//            Dialog dialog = GooglePlayServicesUtil.getErrorDialog(resultCode, activity, 0);
//            if (dialog != null) {
//                ErrorDialogFragment errorFragment = new ErrorDialogFragment();
//                errorFragment.setDialog(dialog);
//                errorFragment.show(getSupportFragmentManager(), LocationUtils.APPTAG);
//            }
            return false;
        }
    }

    public void getLocation() {
        if (servicesConnected()) {
            mLocation = mLocationClient.getLastLocation();
        }
    }
    
	@Override
	public void onConnectionFailed(ConnectionResult connectionResult) {
        if (connectionResult.hasResolution()) {
            try {
                connectionResult.startResolutionForResult(
                        activity,
                        LocationUtils.CONNECTION_FAILURE_RESOLUTION_REQUEST);
            } catch (IntentSender.SendIntentException e) {
                e.printStackTrace();
            }
        } else {

        }
		
	}

	@Override
	public void onConnected(Bundle arg0) {
        if (mUpdatesRequested) {
            startPeriodicUpdates();
        }
	}

	@Override
	public void onDisconnected() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void onLocationChanged(Location location) {
		// TODO Auto-generated method stub
		
	}

}
